#include <QDesktopServices>
#include <QTextDocument>

#include "ctextbrowser.h"

CTextBrowser::CTextBrowser(QWidget *parent): QTextBrowser(parent)
{
    connect(this, SIGNAL(highlighted(QUrl)), this, SLOT(highlight(QUrl)));
    setContextMenuPolicy(Qt::CustomContextMenu);
    //setOpenExternalLinks(true);
}

QVariant CTextBrowser::loadResource(int type, const QUrl& name)
{
    if(type!=QTextDocument::ImageResource)
        return QTextBrowser::loadResource(type, name);

    if(name.scheme()=="std")
    {
        QString path = name.toString();
        path.remove(name.scheme() + "://");
        return QPixmap(":/icons/" + path);
    }

    bool ok;
    QString path = name.path();

    int num = path.toInt(&ok);

    if(ok && (num < m_images.count()))
        return m_images.at(num);

    return QTextBrowser::loadResource(type, name);
}

int CTextBrowser::addImage(QPixmap pix)
{
    debug("Appended image. Count: " + QString::number(m_images.count()+1));
    m_images.append(pix);
    return m_images.count()-1;
}

void CTextBrowser::setSource(const QUrl &url)
{
    QString scheme = url.scheme();
    QString path = url.toString();
    path.remove(scheme + "://");

    bool ok;
    int num = path.toInt(&ok);
    if(ok)
    {
        if(scheme=="image")
        {
            if(num < m_images.count())
                emit saveImage(QPixmap(m_images.at(num).value<QPixmap>()));
        }
        else if(scheme=="file")
            emit saveFile(num);
        else if(scheme=="edit")
            emit editField(num);
        else if(scheme=="delete")
            emit deleteField(num);
        else
        {
            debug("Unknown scheme: " + scheme);
            QDesktopServices::openUrl(url);
        }
    }
    else
        emit error(tr("Internal error. Can't extract resource,"));
}

void CTextBrowser::highlight(const QUrl &url)
{
    QString scheme = url.scheme();

    if(scheme=="edit")
        emit status(tr("Edit field"));
    else if(scheme=="delete")
        emit status(tr("Delete field"));
    else if(scheme=="file")
        emit status(tr("Save file"));
    else if(scheme=="image")
        emit status(tr("Save image"));
    else
        emit status(url.toString());
}
